package DAO;

import java.awt.Checkbox;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.sql.RowSet;

public class UserDao {
	private Connection conn;
	private static final Logger logger = Logger.getLogger(UserDao.class.getName()); // 日志库
	public UserDao(Connection conn) {
		this.conn = conn;
        // 创建一个文件处理器
        try {
        	String path = "." + File.separator + "log" + File.separator + "UserDao.log"; //   ./log/xxx.log
            FileHandler fileHandler = new FileHandler(path);
            fileHandler.setLevel(Level.INFO);

            // 创建一个日志格式化器
            Formatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);

            // 将处理器添加到日志记录器
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	// 注册时候用来注册新用户,返回新用户账号
	public int createUser(String theName, String thePassword) {
		//int userId = 0;
		logger.info("注册时候用来注册新用户,返回新用户账号");
		int account = this.generateUniqueAccount();		
		String sql = "INSERT INTO user (room_id_1, room_id_2, room_id_3, room_id_4, room_id_5, room_id_6,"
		+ " room_id_7, room_id_8, room_id_9, room_id_10, room_num, name, password,account) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
		try {
			PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			for(int i = 1; i <= 10; i++) {
				stmt.setInt(i, -1);
			}						
			stmt.setInt(11, 0);
			stmt.setString(12, theName);
			stmt.setString(13, thePassword);
			stmt.setInt(14, account);
			// 执行插入操作
			stmt.executeUpdate();
	        // 获取生成的主键 ID
	   /*     ResultSet generatedKeys = stmt.getGeneratedKeys();
	        if (generatedKeys.next()) {
	            userId = generatedKeys.getInt(1);
	        }  */
	        stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return account;
	}
	// 根据用户名与密码获取id,也即登录
	// 支持同名
	public int loginGetID(int account, String thePassword) {
		int userId = 0;
		int check = 0;
		String query = "SELECT * FROM user WHERE account = '" + account + "'";
		try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果
            while (resultSet.next()) {
            	check++;
                String password = resultSet.getString("password");
                System.out.println(password);
                System.out.println(thePassword);
                if(password.equals(thePassword)) {
                	System.out.println("成功找到用户！");
                	logger.info("成功找到用户！");
                	userId = resultSet.getInt("user_id");
                }
            }
            stmt.close();
		} catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        // 找到账号，但密码错误
        if (check > 0 && userId == 0) {
        	System.out.println("密码错误");
        	logger.info("密码错误");
        	userId = -1;
        }
        // 没有找到账号
        if (check == 0) {
        	System.out.println("账号不存在");
        	logger.info("账号不存在");
        	userId = -2;
        }
        return userId;
	}
	// 加入一个新聊天室,room_num++,room_id更新
	public int joinNewRoom(int userId, int roomId) {
        String query = "SELECT * FROM user WHERE user_id = " + userId;
        String update1 = "UPDATE user SET room_num = room_num + 1, room_id_";
        String update2 = " = ? WHERE user_id = " + userId;
        int check = 0;
        int roomNum = 0;
        int isIn = 0;
        try {
            // 创建 Statement 对象执行查询
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            // 处理查询结果,只有一条，所以用if
            if (resultSet.next()) {
                roomNum = resultSet.getInt("room_num");
                // 检查是不是已经在房间里了
                for(int i = 1; i <= roomNum; i++) {
                	if(resultSet.getInt("room_id_" + i) == roomId)
                		isIn++;
                }
                System.out.println("Room Num: " + roomNum);
                logger.info("Room Num: " + roomNum);
            }
            stmt.close();
            
            // 要是已经十个房间，那就加入失败
            if(roomNum == 10) {
            	System.out.println("已达最大聊天室数量，不能再加入");
            	logger.info("已达最大聊天室数量，不能再加入");
            	return -2;
            }
            // 要是已经加入该房间，就加入失败
            if(isIn > 0) {
            	System.out.println("已经加入该房间，不能再加入");
            	logger.info("已经加入该房间，不能再加入");
            	return -1;
            }
            
            // 建立 PreparedStatement 对象执行插入
            roomNum++;
            String update = update1 + roomNum + update2;
            System.out.println(update);
            PreparedStatement pstmt = conn.prepareStatement(update);
            pstmt.setInt(1, roomId);
            check = pstmt.executeUpdate(); 
            pstmt.close();
        } catch (Exception e) {
			// TODO: handle exception
        	System.out.println(e);
		}
        if(check > 0) { // 插入行数，检查是否成功
			System.out.println("加入房间成功！");
			logger.info("加入房间成功！");
			return 0;
        } else {
			System.out.println("加入房间失败！");
			logger.info("加入房间失败！");
			return -3;
        }
	}
	// 获得当前所有的聊天室
	public Vector<Integer> getAllRoom(int userId) {
		logger.info("获得当前所有的聊天室");
		Vector<Integer> roomIds = new Vector<>();
		String query = "SELECT * FROM user WHERE user_id = " + userId;
	    try {
	        // 创建 Statement 对象执行查询
	        Statement stmt = conn.createStatement();
	        ResultSet resultSet = stmt.executeQuery(query);
	        // 处理查询结果
	        if (resultSet.next()) {
	            for (int i = 1; i <= 10; i++) {
	            	int roomId = resultSet.getInt("room_id_" + i);
	            	if (roomId == -1)
	            		break;
	            	else 
	            		roomIds.add(roomId);
	            }
	        }
	        stmt.close();
	    } catch (Exception e) {
			// TODO: handle exception
	        System.out.println(e);
		}
	    return roomIds;
	}
	// 退出一个聊天室,因为跟客户端的列表一一对应，所以传index更好操作
	public boolean leaveTheRoom(int userId, int roomId) {
		logger.info("退出一个聊天室");
		// 首先根据roomId进行一些查询
		String query = "SELECT * FROM user WHERE user_id = " + userId;
		int index = -1;
	    try {
	        // 创建 Statement 对象执行查询
	        Statement stmt = conn.createStatement();
	        ResultSet resultSet = stmt.executeQuery(query);
	        // 处理查询结果
	        if (resultSet.next()) {
	        	// 找到该房间的下标
	            for (int i = 1; i <= 10; i++) {
	            	if (resultSet.getInt("room_id_" + i) == roomId) {
	            		index = i;
	            		break;
	            	}
	            }
	        }
	        stmt.close();
	    } catch (Exception e) {
			// TODO: handle exception
	        System.out.println(e);
		}
		
		// 然后根据找到的index进行操作
		int check = 0;
		String update = "UPDATE user SET ";
		for (int i = index; i < 10; i++) {
		    update += "room_id_" + i + " = room_id_" + (i + 1) + ", ";
		}
		update += "room_id_10 = -1, room_num = room_num - 1 WHERE user_id = ?";

		try {
		    PreparedStatement updateStmt = conn.prepareStatement(update);
		    updateStmt.setInt(1, userId);
		    check = updateStmt.executeUpdate();
		    updateStmt.close();
		} catch (Exception e) {
		    System.out.println(e);
		}
		if(check > 0) {
			System.out.println("成功退出！");
			logger.info("成功退出！");
			return true;
		} else {
			System.out.println("退出异常！");
			logger.info("退出异常！");
			return false;
		}
	}
	// 注销账户
	public boolean deleteUser(int userId) {
		String sql = "DELETE FROM user WHERE user_id = ?";
		int check = 0;
		try {
		    PreparedStatement stmt = conn.prepareStatement(sql);
		    stmt.setInt(1, userId);
		    check = stmt.executeUpdate();
		    stmt.close();
		} catch (Exception e) {
		    System.out.println(e);
		}
		
	    if (check > 0) {
	        System.out.println("表项删除成功");
	        logger.info("表项删除成功");
	        return true;
	    } else {
	        System.out.println("未找到匹配的表项");
	        logger.info("未找到匹配的表项");
	        return false;
	    }
	}

// 获取用户的好友
public Hashtable<Integer,String> getAllFriends(int useraccount){
	logger.info("获取用户的好友");
	Hashtable<Integer,String> friends = new Hashtable<Integer,String>();
	String sql = "SELECT * FROM friends WHERE maccount = ?";
	ResultSet rs = null;
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setInt(1, useraccount);
		rs = stmt.executeQuery();
	}catch(SQLException e)
	{
		e.printStackTrace();
	}
	try {
		while(rs.next())
		{
			int faccount = rs.getInt("faccount");
			String fname = rs.getString("fname");
			friends.put(faccount,fname);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return friends;
	}


// 根据账户获取用户id
public int getUserId(int account) {
	logger.info("根据账户获取用户id");
	String sql = "SELECT * FROM user WHERE account = ?";
	ResultSet rs = null;
	int userid = -1;
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setInt(1, account);
		rs = stmt.executeQuery();
	}catch(SQLException e)
	{
		e.printStackTrace();
	}
	try {
		while(rs.next())
		{
			userid = rs.getInt("user_id");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return userid;
	}


//根据用户id获取账户
public int getUserAccount(int userid) {
	logger.info("根据用户id获取账户");
	String sql = "SELECT * FROM user WHERE user_id = ?";
	ResultSet rs = null;
	int account = -1;
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setInt(1, userid);
		rs = stmt.executeQuery();
	}catch(SQLException e)
	{
		e.printStackTrace();
	}
	try {
		while(rs.next())
		{
			account = rs.getInt("account");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return account;
   }


// 根据用户账号获取用户昵称
public String getUserName(int useraccount) {
	logger.info("根据用户账号获取用户昵称");
	String sql = "SELECT * FROM user WHERE account = ?";
	ResultSet rs = null;
	String name = null;
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setInt(1, useraccount);
		rs = stmt.executeQuery();
	}catch(SQLException e)
	{
		e.printStackTrace();
	}
	try {
		while(rs.next())
		{
			name = rs.getString("name");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return name;
  }

public String getUserNameById(int userid) {
	int useraccount = this.getUserAccount(userid);
	return this.getUserName(useraccount);
}

//产生随机账号
public int generateUniqueAccount() {
    int account = 0;
    boolean isUnique = false;
    while (!isUnique) {
        account = new Random().nextInt(100000);
        String sql = "SELECT account FROM user WHERE account = ?";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, account);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                isUnique = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return account;
}

//修改用户名
public boolean modifyName(int account,String name) {
	String sql = "UPDATE user SET name = ? WHERE account = ?";
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, name);
		stmt.setInt(2, account);
		int rows = stmt.executeUpdate();
		
		if(rows > 0) {
			return true;
		}
	}catch(SQLException e)
	{
		e.printStackTrace();
	}	
	return false;
}
  

// 修改密码
public boolean modifyPwd(int account,String pwd) {
	String sql = "UPDATE user SET password = ? WHERE account = ?";
	try
	{
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, pwd);
		stmt.setInt(2, account);
		int rows = stmt.executeUpdate();
		
		if(rows > 0) {
			return true;
		}
	}catch(SQLException e)
	{
		e.printStackTrace();
	}	
	return false;
}
}

